package com.credit.mola.app.utils.analysis.util

import android.app.Application
import android.os.Handler
import android.os.Looper
import com.credit.mola.app.utils.analysis.AnalysisBuilder
import com.credit.mola.app.utils.analysis.bean.FirebaseS2SBean
import com.credit.mola.app.utils.analysis.http.AnalysisHttpUtils
import com.credit.mola.app.utils.analysis.http.UrlHelper
import com.credit.mola.app.utils.log.HHLog
import com.google.android.gms.tasks.Task
import com.google.firebase.analytics.FirebaseAnalytics

/**
 * Firebase
 */
object FirebaseUtil {

    /** firebase app id, 服务端回推firebase事件使用 */
    private var mFirebaseAppId: String = ""

    /** ga4 instance id, 服务端回推firebase事件使用 */
    private var mGa4InstanceId: String = ""

    /**
     * 初始化
     *
     * @param context Application
     */
    fun init(context: Application, success: (String, String) -> Unit) {
        try {
            if (mFirebaseAppId.isBlank()) {
                Thread {
                    if (Looper.getMainLooper() != Looper.myLooper()) {
                        mFirebaseAppId = FirebaseAnalytics.getInstance(context).firebaseInstanceId
                        HHLog.i("mFirebaseAppId=$mFirebaseAppId")

                        if (mFirebaseAppId.isNotBlank()){
                            Handler(Looper.getMainLooper()).post {
                                //回调通知
                                success.invoke(getFirebaseAppId(), getGa4InstanceId())
                            }
                        }
                    } else {
                        HHLog.i("init Firebase ERROR! Cannot call in the main thread, You must call in the other thread")
                    }
                }.start()
            } else {
                Handler(Looper.getMainLooper()).post {
                    //回调通知
                    success.invoke(getFirebaseAppId(), getGa4InstanceId())
                }
            }

            if (mGa4InstanceId.isBlank()) {
                val gResult: Task<String?> = FirebaseAnalytics.getInstance(context).appInstanceId
                gResult.addOnSuccessListener {
                    mGa4InstanceId = it?:""
                    HHLog.i("mGa4InstanceId=$mGa4InstanceId")

                    if (mGa4InstanceId.isNotBlank()){
                        Handler(Looper.getMainLooper()).post {
                            //回调通知
                            success.invoke(getFirebaseAppId(), getGa4InstanceId())
                        }
                    }
                }
            } else {
                //回调通知
                success.invoke(getFirebaseAppId(), getGa4InstanceId())
            }
        } catch (e: Exception) {
            //回调通知
            success.invoke(getFirebaseAppId(), getGa4InstanceId())
        }
    }

    /**
     * 保存 firebase s2s 信息
     */
    fun saveS2SInfo() {
        val path = AnalysisBuilder.pathFirebaseInstall
        val body = FirebaseS2SBean(
            firebaseAppId = getFirebaseAppId(),
            ga4AppInstanceId = getGa4InstanceId()
        ).encrypt(path)
        val url = UrlHelper.combineUrl()
        AnalysisHttpUtils.postData(url,body)
    }

    /**
     * 获取Firebase App Id
     */
    private fun getFirebaseAppId(): String {
        return mFirebaseAppId
    }

    /**
     * 获取Firebase Ga4 instance Id
     */
    private fun getGa4InstanceId(): String {
        return mGa4InstanceId
    }
}